const { Op } = require("sequelize");
const RegionModels = require('../models/region');

class AreaService {
    // 获取所有的省
    public async getAllProvs() {
        const { count, rows } = await RegionModels.findAndCountAll({
            where: {
                level: 1
            }
        })
        return {
            total: count,
            list: rows
        }
    }
    // 获取单个城市（通过省名和城市名）
    public async getCitiesByquery(cityName: string, provName: string) {
         // 不分页直接获取
         const res = await RegionModels.findOne({
            where: {
                [Op.and]: [
                    {
                        level: 2
                    },
                    {
                        name: cityName
                    }
                ]
            }
        })
        const ans = await RegionModels.findOne({
            where: {
                [Op.and]: [
                    {
                        level: 1
                    },
                    {
                        id: res.dataValues.pid
                    }
                ]
            }
        })
        return (ans && ans.dataValues.name == provName) ? res.dataValues : null
    }
    // 通过id获取城市或者区县
    public async getInfoById(id: number) {
        const { count, rows } = await RegionModels.findAndCountAll({
            where: {
                pid: id
            }
        })
        return {
            total: count,
            list: rows
        }
    }
}

module.exports = new AreaService()
// 解决同目录下多个ts文件都引入Op,会报错的问题
export {}